// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// 树转数组
export function treeToArray(tree = []) {
	let arr = []
	tree.forEach(item => {
		let children = item.children
		delete item.children
		arr.push(item)
		if(children) arr.push(...treeToArray(children))
	})
	return arr
}

// 获取文件类型
export function getFileType(filePath){
	const fileName = filePath.split('.')
	return fileName[fileName.length - 1]
}

// 获取文件名字
export function getFileName(filePath){
	const fileName = filePath.split('/')
	return fileName[fileName.length - 1]
}

// 获取未来几天的时间
export function getFutureDate(days, pattern) {
  const futureDate = new Date()
  futureDate.setDate(futureDate.getDate() + days)
  return parseTime(futureDate, pattern)
}

// 倒计时
export function countTime(timeStr) {
	let nowTimeStamp = +new Date()
	let endTimeStamp = +new Date(timeStr)
	let seconds = (endTimeStamp - nowTimeStamp) / 1000
	let minute = parseInt(seconds / 60 % 60)
	minute = minute < 10 ? '0' + minute : minute
	let hour = parseInt(seconds / 60 / 60 % 24)
	hour = hour < 10 ? '0' + hour : hour
	if(seconds < 0) return ''
	else return hour + '小时' + minute + '分'
}

// 时间戳转换为时分秒
export function timestampToTime(timestamp) {
    let hours = Math.floor(timestamp  / 3600)
    let minutes = Math.floor((timestamp % 3600) / 60)
    let seconds = timestamp % 60
	let formatHours = hours < 10? '0' + hours : hours
	let formatMinutes = minutes < 10? '0' + minutes : minutes
	let formatSeconds = seconds < 10? '0' + seconds : seconds
	if(formatHours === '00') return formatMinutes + ":" + formatSeconds
	else return formatHours + ":" + formatMinutes + ":" + formatSeconds
}


// 获取字典中的标签
export function getLabel(columns, value) {
	let cur = columns.find(item => item.value!== '' && item.value == value)
	if(cur) return cur.label
	else return ''
}